/**
 * Created by tcrow on 2017/1/12 0012.
 */
var module = app;

module.directive('ngConfirmClick', [
    function(){
        return {
            link: function (scope, element, attr) {
                var msg = attr.ngConfirmClick || "Are you sure?";
                var clickAction = attr.confirmedClick;
                element.bind('click',function (event) {
                    if ( window.confirm(msg) ) {
                        scope.$eval(clickAction)
                    }
                });
            }
        };
    }]);
module.controller('envController', ['$scope','$window', 'ngDialog', '$http','Notification',function ($scope,$window, ngDialog, $http,Notification) {
    $scope.paginationConf = {
        currentPage: 1,
        totalItems: 0,
        itemsPerPage: 10,
        pagesLength: 15,
        perPageOptions: [10],
        rememberPerPage: 'perPageItems',
        onChange: function () {
            $scope.showenvList(this.currentPage,this.totalItems);

        }
    };
    $scope.status=['已废弃','使用中'];
    $scope.allenvList = [];
    $scope.envShowList = [];
    $http({
        method: "GET",
        url: "envdic/list.query"
    }).success(function (resp) {
        if(resp.status ==0){
            $scope.allenvList = resp.data;
            console.log($scope.allenvList);
            console.log(JSON.stringify(resp));
            $scope.showenvList(1,$scope.allenvList.length);

        }else {
            Notification.error({message: resp.errMsg, delay: 5000});
        }

    });
    
    $scope.regionCode='';
    $scope.envCode='';
    /**
     * 域名变动,更新环境
     */
    $scope.changeRegion=function(regionCode){
    	$scope.regionCode=regionCode;
    	console.log(regionCode);
    	console.log($scope.ngDialogData.allEnvNameList);
    	
    	 $http({
    	        method: "POST",
    	        url: "script/findEnvCodeByRegionCode.query",
    	        data:regionCode
    	    }).success(function (resp) {
    	        if(resp.status ==0){
    	        	$scope.ngDialogData.allEnvNameList=resp.data.envMap;
    	        }else {
    	            Notification.error({message: resp.errMsg, delay: 5000});
    	        }

    	    });
    }
    
    //部门变动
   // $scope.item=[];
    $scope.changeDept=function(deptCode){
    	 $http({
    	        method: "POST",
    	        url: "envdic/findDeptByDeptCode.query",
    	        data:deptCode
    	    }).success(function (resp) {
    	    	debugger;
    	        if(resp.status ==0){
    	        	$scope.item.sysCodes=resp.data.sysCodes;
    	        }else {
    	            Notification.error({message: resp.errMsg, delay: 5000});
    	        }

    	    });
    }
    /**
     * 域名和环境变动更新集群名
     */
    $scope.changeEnv=function(envCode){
    	console.log($scope.regionCode);
    	console.log(envCode);
    	 $http({
 	        method: "POST",
 	        url: "envdic/findClusterByRegionCodeAndEnvCode.query",
 	       data:{
 	    	  regionCode:$scope.regionCode,
 	    	  envCode:envCode
           }
 	    }).success(function (resp) {
 	        if(resp.status ==0){
 	        	$scope.ngDialogData.allClusterList=resp.data.clusterMap;
 	        }else {
 	            Notification.error({message: resp.errMsg, delay: 5000});
 	        }

 	    });
    }
    
    $scope.filterStr="";
    $scope.filterVersion="";
    $scope.$watch('filterStr', function() {
        $scope.filterList(1);
    });
    $scope.$watch('filterVersion', function() {
        $scope.filterList(1);
    });
    $scope.filterList = function (currentPage) {
        var lowExceptStr =  $scope.filterStr;
        var lowExceptStrVersion =  $scope.filterVersion;
        var canShowList = [];
        $scope.allenvList.forEach(function(element) {
        	var topicName=toString(element.topicName);
                if (element.enviroName.indexOf(lowExceptStr) != -1 && element.regionName.indexOf(lowExceptStrVersion) != -1){
                    canShowList.push(element);
                }
         
        });
        $scope.paginationConf.totalItems =canShowList.length;
        var perPage = $scope.paginationConf.itemsPerPage;
        var from = (currentPage - 1) * perPage;
        var to = (from + perPage)>canShowList.length?canShowList.length:from + perPage;
        $scope.envShowList = canShowList.slice(from, to);
    };

    $scope.showenvList = function (currentPage,totalItem) {
        var perPage = $scope.paginationConf.itemsPerPage;
        var from = (currentPage - 1) * perPage;
        var to = (from + perPage)>totalItem?totalItem:from + perPage;
        console.log($scope.allenvList);
        console.log(from)
        console.log(to)
        $scope.envShowList = $scope.allenvList.slice(from, to);
        $scope.paginationConf.totalItems = totalItem ;
        console.log($scope.envShowList)
        console.log($scope.paginationConf.totalItems)
        $scope.filterList(currentPage);
    };
    $scope.downLoadEnv = function (envInfo) {
        console.log(envInfo);
        var request = JSON.parse(JSON.stringify(envInfo));
        console.log(request);
        $http({
            method: "POST",
            url: "env/downLoadEnv.do",
            data:request,
            responseType: 'arraybuffer'
        }).success(function (response, status, headers, config) { 
        	var fileName=headers('Content-Disposition');
	        fileName = decodeURI(fileName);
	        var url = URL.createObjectURL(new Blob([response]));
	        var a = document.createElement('a');
	        document.body.appendChild(a); //此处增加了将创建的添加到body当中
	        a.href = url;
	        a.download = fileName;
	        a.target = '_blank';
	        a.click();
	        a.remove(); //将a标签移除
        });
    };
    $scope.deleteEnv= function (env) {
        $http({
            method: "POST",
            url: "env/deleteEnv.do",
            params:{
                env:env
            }
        }).success(function (resp) {
            if(resp.status ==0){
                Notification.info({message: "delete success!", delay: 2000});
            }else {
                Notification.error({message: resp.errMsg, delay: 2000});
            }
        });
    };
    
    $scope.postUpdateenvRequest = function (envRequestItem) {
            console.log(envRequestItem);
            var request = JSON.parse(JSON.stringify(envRequestItem));
            console.log(request);
            $http({
                method: "POST",
                url: "envdic/update.do",
                data:request
            }).success(function (resp) {
                if(resp.status ==0){
                	
                    $http({
                        method: "GET",
                        url: "envdic/list.query"
                    }).success(function (resp) {
                        if(resp.status ==0){
                            $scope.allenvList = resp.data;
                            console.log($scope.allenvList);
                            console.log(JSON.stringify(resp));
                            $scope.showenvList(1,$scope.allenvList.length);
                            $window.location.reload();
                        }else {
                            Notification.error({message: resp.errMsg, delay: 5000});
                        }

                    });
                }else {
                    Notification.error({message: resp.errMsg, delay: 2000});
                }
            });
        };


        function haveChineseBiaoDian(text)
        {
            //匹配这些中文标点符号 。 ？ ！ ， 、 ； ： “ ” ‘ ' （ ） 《 》 〈 〉 【 】 『 』 「 」 ﹃ ﹄ 〔 〕 … — ～ ﹏ ￥
            var reg = /[\u3002|\uff1f|\uff01|\uff0c|\u3001|\uff1b|\uff1a|\u201c|\u201d|\u2018|\u2019|\uff08|\uff09|\u300a|\u300b|\u3008|\u3009|\u3010|\u3011|\u300e|\u300f|\u300c|\u300d|\ufe43|\ufe44|\u3014|\u3015|\u2026|\u2014|\uff5e|\ufe4f|\uffe5]/;
            if(reg.test(text)){
                return true;//是中文标点符号
            }else{
                return false;//不是中文标点符号
            }
        }
        
        $scope.postenvRequest = function (envRequestItem) {
            console.log(envRequestItem);
            var request = JSON.parse(JSON.stringify(envRequestItem));
            console.log(request);
           
            if(request.regionName==null || request.regionName==''){
            	alert("域名不能为空");
            	return;
            }
            if(request.enviroCode==null || request.enviroCode==''){
            	alert("环境不能为空");
            	return;
            }
            if(request.cluster==null || request.cluster==''){
            	alert("集群名称不能为空");
            	return;
            }
            if(haveChineseBiaoDian(request.cluster)){
            	alert("集群名称含有中文标点符号");
            	return;
            }
            if(request.nameserver==null || request.nameserver==''){
            	alert("nameserver不能为空");
            	return;
            }
            if(haveChineseBiaoDian(request.nameserver)){
            	alert("nameserver含有中文标点符号");
            	return;
            }
            $http({
                method: "POST",
                url: "envdic/save.do",
                data:request
            }).success(function (resp) {
                if(resp.status ==0){
                	
                    $http({
                        method: "GET",
                        url: "envdic/list.query"
                    }).success(function (resp) {
                        if(resp.status ==0){
                            $scope.allenvList = resp.data;
                            console.log($scope.allenvList);
                            console.log(JSON.stringify(resp));
                            $scope.showenvList(1,$scope.allenvList.length);
                            $window.location.reload();
                        }else {
                            Notification.error({message: resp.errMsg, delay: 5000});
                        }

                    });
                   
                }else {
                    Notification.error({message: resp.errMsg, delay: 2000});
                }
            });
        };
        $scope.postDeptRequest = function (deptRequestItem) {
        	debugger;
        	var request = JSON.parse(JSON.stringify(deptRequestItem));
        	
        	$http({
        		method: "POST",
        		url: "envdic/saveDept.do",
        		data:request
        	}).success(function (resp) {
        		if(resp.status ==0){
        			
        			$http({
        				method: "GET",
        				url: "envdic/list.query"
        			}).success(function (resp) {
        				if(resp.status ==0){
        					$scope.allenvList = resp.data;
        					console.log($scope.allenvList);
        					console.log(JSON.stringify(resp));
        					$scope.showenvList(1,$scope.allenvList.length);
        					$window.location.reload();
        				}else {
        					Notification.error({message: resp.errMsg, delay: 5000});
        				}
        				
        			});
        			
        		}else {
        			Notification.error({message: resp.errMsg, delay: 2000});
        		}
        	});
        };
        $scope.postPermissionRequest = function (permissionRequestItem) {
        	debugger;
        	var request = JSON.parse(JSON.stringify(permissionRequestItem));
        	
        	$http({
        		method: "POST",
        		url: "envdic/savePermission.do",
        		data:request
        	}).success(function (resp) {
        		if(resp.status ==0){
        			
        			$http({
        				method: "GET",
        				url: "envdic/list.query"
        			}).success(function (resp) {
        				if(resp.status ==0){
        					$scope.allenvList = resp.data;
        					console.log($scope.allenvList);
        					console.log(JSON.stringify(resp));
        					$scope.showenvList(1,$scope.allenvList.length);
        					$window.location.reload();
        				}else {
        					Notification.error({message: resp.errMsg, delay: 5000});
        				}
        				
        			});
        			
        		}else {
        			Notification.error({message: resp.errMsg, delay: 2000});
        		}
        	});
        };

    $scope.openSendenvMessageDialog = function (env) {
        ngDialog.open({
            template: 'sendenvMessageDialog',
            controller: 'sendenvMessageDialogController',
            data: {
                env: env
            }
        });
    };

    $scope.openUpdateDialog = function (env) {
        $http({
            method: "GET",
            url: "envdic/examineenvConfig.query",
            params:{
                env:env
            }
        }).success(function (resp) {
            if(resp.status ==0){
                $scope.openCreateOrUpdateDialog(resp.data);
            }else {
                Notification.error({message: resp.errMsg, delay: 2000});
            }
        });
    };

    $scope.allSysNameList=[];
    $scope.allEnvNameList=[];
    $scope.allRegionNameList=[];
    $scope.allClusterList=[];
    $scope.reqOrRes=[{code:"REQUEST",name:"请求"},{code:"RESPONSE",name:"响应"}];
    $scope.openCreateEnvDialog = function (request) {
        var bIsUpdate = true;

        if(request == null){
            request = [{
            	regionName:"",
            	enviroCode:"",
            	cluster:"",
            	nameserver:""
            }];
            bIsUpdate = false;
        }
        $http({
            method: "GET",
            url: "envdic/listRegionAndEnv.query"
        }).success(function (resp) {
            if(resp.status ==0){
                console.log(resp.data);
                ngDialog.open({
                    template: 'envCreateDialog',
                    controller: 'envController',
                    data:{
                        envRequestList:request,
                        allEnvNameList:resp.data.envMap,
                        allRegionNameList:resp.data.regionMap,
                        allClusterList:resp.data.clusterMap,
                        bIsUpdate:bIsUpdate
                    }
                });
            }
        });
    }

    
    
    $scope.openAddEnvDialog = function () {
        $scope.openCreateEnvDialog(null);
    }
    $scope.openAddSysDialog = function () {
        $scope.openCreateSysDialog(null);
    }
    $scope.info={
        	regionName:"",
        	enviroCode:"",
        	cluster:"",
        	servUserName:"",
        	servOfferName:"",
        	servCode:"",
            servName:"",
            versionCode:"",
            reqOrRes:""
        };
    $scope.openModifyEnvDialog = function (id) {
        var bIsUpdate = false;
        $http({
            method: "POST",
            url: "envdic/findEnvDicById.query",
        	 data: {
                 id: id
             }
        }).success(function (resp) {
            if(resp.status ==0){
                console.log(resp.data);
//                $scope.info=resp.data.environDic;
                ngDialog.open({
                    template: 'envModifyDialog',
                    controller: 'envController',
                    data:{
                    	item:resp.data.environDicList,
//                    	allSysNameList:resp.data.sysMap,
                        allEnvNameList:resp.data.envMap,
                          allRegionNameList:resp.data.regionMap
//                        allClusterList:resp.data.clusterMap,
//                        reqOrRes:$scope.reqOrRes,
//                        bIsUpdate:bIsUpdate
                    }
                });
            }
        });
    }
    $scope.openModifyDeptDialog = function (request) {
    	 var bIsUpdate = true;

         if(request == null){
             request = {
             	code:"",
             	name:"",
             	newSysCodes:"",
             	sysCodes:""
             };
             bIsUpdate = false;
         }
    	$http({
    		method: "GET",
    		url: "envdic/listAllDept.query"
    	}).success(function (resp) {
    		if(resp.status ==0){
    			console.log(resp.data);
//                $scope.info=resp.data.environDic;
    			ngDialog.open({
    				template: 'deptModifyDialog',
    				controller: 'envController',
    				data:{
    					item:request,
                    	allSysNameList:resp.data.sysMap,
    					allDeptList:resp.data.deptInfos
//    					allRegionNameList:resp.data.regionMap
//                        allClusterList:resp.data.clusterMap,
//                        reqOrRes:$scope.reqOrRes,
//                        bIsUpdate:bIsUpdate
    				}
    			});
    		}
    	});
    }
    
    $scope.openModifyPermissionDialog = function (request) {
   	 var bIsUpdate = true;

        if(request == null){
            request = {
            	name:"",
            	permissionId:""
            };
            bIsUpdate = false;
        }
   	$http({
   		method: "GET",
   		url: "envdic/listAllPermission.query"
   	}).success(function (resp) {
   		if(resp.status ==0){
   			console.log(resp.data);
//               $scope.info=resp.data.environDic;
   			ngDialog.open({
   				template: 'userPermissionModifyDialog',
   				controller: 'envController',
   				data:{
   					item:request,
   					allUserInfoList:resp.data.userInfos,
   					allUserPermissionList:resp.data.userPermissions
//   					allRegionNameList:resp.data.regionMap
//                       allClusterList:resp.data.clusterMap,
//                       reqOrRes:$scope.reqOrRes,
//                       bIsUpdate:bIsUpdate
   				}
   			});
   		}
   	});
   }
    function StringBuffer() {
        this.__strings__ = [];
    };
    StringBuffer.prototype.append = function(str) {
        this.__strings__.push(str);
    };
    StringBuffer.prototype.toString = function() {
        return this.__strings__.join('');
    };
    $scope.handleArrays=function(consumerGroup){
    	var buffer = new StringBuffer();//声明一个对象
       
    	//alert(consumerGroup);
    	var obj=[];
        var result = "";
    	obj = JSON.parse(consumerGroup); //由JSON字符串转换为JSON对象
    	
    	for(var i=0;i<obj.length;i++){
    		if(obj.length>1){
    			buffer.append(i+1+"."+obj[i]+"、");//追加字符串，下同
    		}else{ 
    			buffer.append(obj[i]+"、");//追加字符串，下同}
    		}
    		
    		// buffer.append('。');//追加字符串，下同
    		// result+=(i+1+"."+obj[i]+"");
    	}
    	//alert(date.replace(/(。)(\d)/g,"$1\n$2"));
    	return buffer.toString().substr(0, buffer.toString().length-1);;
    	//return result;
    }
}]);




